-- SPDX-FileCopyrightText: Adam Evyčędo
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

---@diagnostic disable-next-line: lowercase-global
function getVehicles(north, west, south, east)
	local http = require("http")
	local json = require("json")

	local error_struct = {
		httpResponseCode=0,
		message="",
		willNextRequestFail=false
	}

	local response, error_message = http.get("https://v6.vbb.transport.rest/radar", {
		query="north=" .. north .. "&west=".. west .. "&south=".. south .. "&east=" .. east .."&polylines=false&frames=0&pretty=false",
		timeout="30s"
	})

	if response == nil then
		error_struct.message = "while getting vehicles: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	if response.status_code ~= 200 then
		error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
		error_struct.httpResponseCode = response.status_code
		error_struct.willNextRequestFail = true
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	---@diagnostic disable-next-line: redefined-local
	local struct, error_message = json.decode(response.body)

	if struct == nil then
		error_struct.message = "while decoding vehicles: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	local updates = {}
	updates[''] = {
  	vehicleID="",
  	latitude=0,
  	longitude=0,
  	speed=0,
  	bearing=0,
  	lineID="",
  	headsign="",
  	tripID="",
	}

	for _, entry in ipairs(struct.movements) do
	  updates[entry.tripId] = {
	    headsign=entry.direction,
	    lineID=entry.line.id,
	    latitude=entry.location.latitude,
	    longitude=entry.location.longitude
	  }
	end

	---@diagnostic disable-next-line: redefined-local
	local result, error_message = json.encode(updates)

	if result == nil then
		error_struct.message = "while encoding result: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	return result, ""
end
